<?php
namespace common\repositories\myhtsq;

use common\entities\myhtsq\ContractPayinfoEntity;
use common\repositories\BaseRepository;
use common\support\Helper;
use yii\base\Exception;

class ContractPayinfoRepository extends BaseRepository
{
    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    public static function getPayInfoLists($pageParam, $params)
    {
        $query = ContractPayinfoEntity::find();

        if (!empty($params['pay_way'])) {
            $query->andWhere(['pay_way' => $params['pay_way']]);
        }

        if (!empty($params['product_name'])) {
            $query->andWhere(['product_name' => $params['product_name']]);
        }

        if (isset($params['refund_status'])) {
            $query->andWhere(['refund_status' => $params['refund_status']]);
        }

        if (!empty($params['beginDate'])) {
            $query->andWhere(['>=', 'pay_time', $params['beginDate']]);
        }

        if (!empty($params['endDate'])) {
            $query->andWhere(['<=', 'pay_time', $params['endDate']]);
        }

        //$sql = clone $query;
        //var_dump($sql->createCommand()->getRawSql());die;
        if (!empty($params['keyword'])) {
            $query->andWhere(['or', ['order_code' => $params['keyword']], ['pay_amount' => $params['keyword']], ['pay_order_id' => $params['keyword']]]);
        }

        $count = $query->count(); //条数
        $totalAmount = 0;
        foreach($query->all() as $item){
            $totalAmount += empty($item->pay_amount)?0:$item->pay_amount;
        }
        $itemsAll= $query->asArray()->all();

        $offset = Helper::getSkipByPageParam($pageParam);
        $query->offset($offset)->limit($pageParam->pageSize); //分页
        $items = $query->asArray()->all();

        return ['total' => $count, 'items' => $items, 'itemsAll' => $itemsAll, 'total_pay_amount'=>$totalAmount];
    }

    /**
     * 更新回款状态
     * @param $contract_id
     *
     * @return int
     * @throws \yii\db\Exception
     */
    public static function updateRefundStatus($contract_id = '', $status = 1)
    {
        try {
            return ContractPayinfoEntity::getDb()->createCommand(
                'UPDATE ' . ContractPayinfoEntity::tableName() . ' SET `refund_status` = ' . $status . ' WHERE `contract_id`="' . $contract_id . '"')->execute();
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 根据合同id获取支付列表
     * @param string $contract_id
     *
     * @return mixed
     */
    public static function getPayInfoByContractId($contract_id  = '')
    {
        return ContractPayinfoEntity::find()->where(['contract_id' => $contract_id])->asArray()->all();
    }

}